package com.tttshaoqi.server.controller;

import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.common.utils.EmpHolder;
import com.tttshaoqi.pojo.dto.EmployeeDTO;
import com.tttshaoqi.server.mapper.UserMapper;
import com.tttshaoqi.pojo.entity.User;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
@Validated
@RequiredArgsConstructor
public class UserController {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @GetMapping("/me")
    public Result<User> me() {
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        User u = userMapper.findById(emp.getId());
        return u == null ? Result.error("用户不存在") : Result.success(u);
    }

    @PostMapping("/profile")
    public Result<?> updateProfile(@RequestBody UpdateProfileReq req) {
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        User u = userMapper.findById(emp.getId());
        if (u == null) return Result.error("用户不存在");
        u.setNickname(req.getNickname());
        u.setAvatarUrl(req.getAvatarUrl());
        u.setBio(req.getBio());
        userMapper.updateProfile(u);
        return Result.success();
    }

    @PostMapping("/password")
    public Result<?> changePassword(@RequestBody ChangePasswordReq req) {
        EmployeeDTO emp = EmpHolder.getEmp();
        if (emp == null) return Result.error("未登录");
        User u = userMapper.findById(emp.getId());
        if (u == null) return Result.error("用户不存在");
        if (!passwordEncoder.matches(req.getOldPassword(), u.getPasswordHash())) {
            return Result.error("原密码错误");
        }
        userMapper.updatePassword(u.getId(), passwordEncoder.encode(req.getNewPassword()));
        return Result.success();
    }

    @Data
    public static class UpdateProfileReq {
        private String nickname;
        private String avatarUrl;
        private String bio;
    }

    @Data
    public static class ChangePasswordReq {
        @NotBlank
        private String oldPassword;
        @NotBlank
        private String newPassword;
    }
}
